package com.seqb.manage.loupan.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.seqb.common.ResultVo;
import com.seqb.common.config.SeqbConfig;
import com.seqb.common.mybatis.WrapperHandler;
import com.seqb.manage.loupan.dao.LoupanDao;
import com.seqb.manage.loupan.domain.LoupanDO;
import com.seqb.manage.loupan.service.LoupanService;
import com.seqb.utils.DateUtils;
import com.seqb.utils.ExcelExportUtils;
import com.seqb.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.*;

/**
 * @author lilinshen
 * @title 楼盘信息表
 * @description 请填写相关描述
 * @date 2020-01-18
 */
@Service
public class LoupanServiceImpl implements LoupanService {
    @Autowired
    private LoupanDao loupanDao;
    @Autowired
    private SeqbConfig seqbConfig;
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public LoupanDO get(Long id) {
        return loupanDao.selectById(id);
    }

    @Override
    public Page<LoupanDO> list(Map<String, Object> map) {
        if (null != map && null != map.get("pageNumber") && null != map.get("pageSize")) {
            PageHelper.startPage(Integer.valueOf(map.get("pageNumber").toString()), Integer.valueOf(map.get("pageSize").toString()));
        } else {
            PageHelper.startPage(1, Integer.MAX_VALUE);
        }
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, LoupanDO.class);
        return (Page<LoupanDO>) loupanDao.selectList(queryWrapper);
    }

    @Override
    public int count(Map<String, Object> map) {
        QueryWrapper queryWrapper = WrapperHandler.genQueryWrapper(map, LoupanDO.class);
        return loupanDao.selectCount(queryWrapper);
    }

    @Override
    @Transactional
    public int save(LoupanDO loupan) {
        return loupanDao.insert(loupan);
    }

    @Override
    @Transactional
    public int update(LoupanDO loupan) {
        return loupanDao.updateById(loupan);
    }

    @Override
    @Transactional
    public int remove(Long id) {
        return loupanDao.deleteById(id);
    }

    @Override
    @Transactional
    public int batchRemove(Long[] ids) {
        return loupanDao.deleteBatchIds(Arrays.asList(ids));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultVo reptile() {
        try {
            //先删除原来数据
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("is_delete", "0");
            loupanDao.delete(queryWrapper);

            //再爬取最新数据
            String baseUrl = "https://zs.fang.ke.com/loupan/pg%s/?_t=1";
            for (int page = 1; page < 36; page++) {
                String requestUrl = String.format(baseUrl, page);
                ResultVo resultVo = reptileLoupanData(requestUrl);
                if (String.valueOf(resultVo.get("code")).equals("0")) {
                    String data = String.valueOf(resultVo.get("data"));
                    JSONObject dataObject = JSON.parseObject(data);
                    String errno = dataObject.getString("errno");
                    if (!errno.equals("0")) {
                        return ResultVo.error();
                    }
                    JSONObject dataObject1 = dataObject.getJSONObject("data");
                    JSONArray listArray = dataObject1.getJSONArray("list");
                    if (null != listArray && listArray.size() > 0) {
                        for (int i = 0; i < listArray.size(); i++) {
                            JSONObject itemData = listArray.getJSONObject(i);
                            String city = itemData.getString("city_name");
                            String district = itemData.getString("district");
                            String name = itemData.getString("title");
                            String address = itemData.getString("store_addr");
                            String areaRange = itemData.getString("resblock_frame_area_range");
                            String roomDesc = itemData.getString("frame_rooms_desc");
                            double averagePrice = itemData.getDouble("reference_avg_price");
                            double averagePriceUnit = itemData.getDouble("avg_price_start");
                            String houseType = itemData.getString("house_type");
                            String decoration = itemData.getString("decoration");
                            String saleStatus = itemData.getString("sale_status");
                            double totalPriceStart = itemData.getDouble("total_price_start");
                            String coverPic = itemData.getString("cover_pic");
                            String url = itemData.getString("url");
                            String tags = itemData.getJSONArray("tags").toJSONString();
                            //下载封面图片
                            String fileName = UUID.randomUUID() + ".jpg";
                            String fileUrl = "/files/" + FileUtils.generatePath() + fileName;
                            String filePath = seqbConfig.getUploadPath() + FileUtils.generatePath() + fileName;
                            boolean flag = FileUtils.downloadFile(coverPic, filePath);
                            if (flag) {
                                coverPic = fileUrl;
                            }
                            if (!StringUtils.isEmpty(url)) {
                                url = "https://zs.fang.ke.com" + url;
                            }
                            if (StringUtils.isEmpty(city)) {
                                city = "中山市";
                            }
                            LoupanDO saveDO = new LoupanDO();
                            saveDO.setCity(city);
                            saveDO.setDistrict(district);
                            saveDO.setName(name);
                            saveDO.setAddress(address);
                            saveDO.setAreaRange(areaRange);
                            saveDO.setRoomDesc(roomDesc);
                            saveDO.setAveragePrice(averagePrice);
                            saveDO.setAveragePriceUnit(averagePriceUnit);
                            saveDO.setHouseType(houseType);
                            saveDO.setDecoration(decoration);
                            saveDO.setSaleStatus(saleStatus);
                            saveDO.setTotalPriceStart(totalPriceStart);
                            saveDO.setCoverPic(coverPic);
                            saveDO.setUrl(url);
                            saveDO.setTags(tags);
                            loupanDao.insert(saveDO);
                        }
                    }
                }
            }
            return ResultVo.ok();
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return null;
    }

    @Override
    public void export(Map<String, Object> params, HttpServletResponse response) {
        try (OutputStream out = response.getOutputStream()) {
            // 设置导出文件名信息
            String filename = DateUtils.format(new Date(), "yyyyMMddHHmmss") + ".xls";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes(), "iso-8859-1"));
            // 查询出需要导出的数据list
            QueryWrapper queryWrapper = new QueryWrapper();
            List<LoupanDO> list = loupanDao.selectList(queryWrapper);
            if (null != list && list.size() > 0) {
                for (LoupanDO loupan : list) {
                    String tags = loupan.getTags();
                    if (!StringUtils.isEmpty(tags)) {
                        tags = tags.substring(1, tags.length() - 1);
                        loupan.setTags(tags);
                    }
                }
            }
            // 导出到excel文件
            ExcelExportUtils.exportToFile(list, out, LoupanDO.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 爬取中山楼盘的信息
     */
    public ResultVo reptileLoupanData(String requestUrl) {
        try {
            HttpHeaders headers = new HttpHeaders();
            MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>();
            HttpMethod httpMethod = HttpMethod.GET;
            HttpEntity httpEntity = new HttpEntity(requestMap, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(requestUrl, httpMethod, httpEntity, String.class);
            HttpStatus status = responseEntity.getStatusCode();
            if (status.equals(HttpStatus.OK)) {
                String resultData = responseEntity.getBody();
                return ResultVo.ok().put("data", resultData);
            }
            return ResultVo.error();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultVo.error();
    }

}